% % File		:	verity/ppg_0_1_display
% % Description	:   for Heart Rate Algorithm
% % Fuction		:	PPG signal display
% % Author		:	@hiyangdong
% % Version		:	V0.1
% % Time		:	12 Jan. 2016

% 0.1.1 read data and orignal calculate
clear all
orignal_txt = textread('PAH0112_1224.txt','%s');    %read txt file data 32bit with 4byte and Low byte first
orignal_dec = hex2dec(orignal_txt);                 %hex 2 dec every byte
orignal_num = length(orignal_dec);                  %length of the orignal data
ppg_num  = orignal_num/4;                           %length of the PPG data
ppg_data = zeros(1,ppg_num);                        %generate an 1-by-length empty array

% 0.1.2 convert orignal hexadecimal data to ppg 32bit array
j=1;
for i=1:4:orignal_num
    ppg_data(j)=(orignal_dec(i)+(orignal_dec(i+1)*256)+(orignal_dec(i+2)*256*256)+(orignal_dec(i+3)*256*256*256));
    j=j+1;
end

% 0.1.3 time domain analysis
ppg_num = length(ppg_data);
sampletime = 0.02;          %sample time that unit is second
t = 0:sampletime:(ppg_num-1) * sampletime;      %time point

% 0.1.4 time domain plot
subplot(2,1,1);
plot(t,ppg_data,'k');
hold on
title('Time domain PPG data');

% 0.1.5 frequency domain basic analysis
samplefreq=1/sampletime;    %sample frequency that unit is Hz
f=samplefreq*(0:(ppg_num-1))/ppg_num;           %frequency point

% 0.1.6 frequency domain offset calculate analysis
% sampledata_ave=0;
% for i=1:ppg_num
%     sampledata_ave = sampledata_ave+ppg_data(i);
% end
% sampledata_ave=sampledata_ave/ppg_num;
% sampledata_offset=ppg_data-sampledata_ave;

% 0.1.6.1 modify the average algorithm
sampledata_offset=ppg_data-mean(ppg_data);

% 0.1.7 frequency domain FFT analysis
fft_sampledata=fft(sampledata_offset);
% fft_sampledata=fftshift(fft_sampledata1);
unit_fft=abs(fft_sampledata);

% 0.1.8 frequency domain plot
N=ppg_num;
subplot(2,1,2)
plot(f(1:N/2),unit_fft(1:N/2),'k');
grid on
title('Frequency domain PPG data ');

% 0.2.1 peaks and throughs detection
ds=diff(ppg_data);
filter=find(ds(2:end)==0)+1;%%find zeros
ds(filter)=ds(filter-1);%%replace zeros
ds=sign(ds);
ds=diff(ds);
throughs=find(ds>0);
peaks=find(ds<0);

% 0.2.2 peaks and throughs addtional plot
subplot(2,1,1);
plot(t(peaks+1),ppg_data(peaks+1),'or');
plot(t(throughs+1),ppg_data(throughs+1),'b*');

